package top.mengchaob.deploy.util;

import top.mengchaob.deploy.table.HostDo;
import top.mengchaob.deploy.table.HostServerDO;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年04月27日 12:47
 * @description:
 */
public class SSHUtil {
    private static Logger logger = LoggerFactory.getLogger(SSHUtil.class);
    public static Session getSession(HostServerDO hostServerDO) throws JSchException {
        HostDo hostDo = hostServerDO.getHostDo();
        String name = hostDo.getUserName();
        String host = hostDo.getHost();
        int port = hostDo.getPort();
        String password = hostDo.getPassWord();
        JSch jsch = new JSch();
        Session session = null;
        session = jsch.getSession(name,host,port);
        int setoutTime = 30000;
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(hostServerDO.getTimeOut()); // 设置timeout时间
        logger.debug("获取session成功");
        return session;
    }

    public static ChannelSftp getChannelSftp(HostServerDO hostServerDO) throws JSchException {
        Session session = SSHUtil.getSession(hostServerDO);
        session.connect();
        logger.debug("正在打开SFTP通道...");
        Channel channel = session.openChannel("sftp"); // 打开SFTP通道
        logger.debug("已经打开SFTP通道...");
        return (ChannelSftp) channel;
    }
    public static ChannelSftp getChannelSftp(Session session ) throws JSchException {
        session.connect();
        logger.debug("正在打开SFTP通道...");
        Channel channel = session.openChannel("sftp"); // 打开SFTP通道
        logger.debug("已经打开SFTP通道...");
        return (ChannelSftp) channel;
    }

}
